var lockReconnect = false // 是否允许重新连接
var timeout = 1000 * 20 // 心跳间隔
var reTimeout = 1000 * 10 // 重连间隔
var timeoutTimer = null // 心跳定时器
var reTimeoutTimer = null // 重连定时器
var webSocket = null
var userId = $("#userId").val()

function heartCheckStart () {
  timeoutTimer = setTimeout(function () {
    webSocket.send('HeartBeat')
  }, timeout)
}

function heartCheckReset () {
  clearTimeout(timeoutTimer)
  heartCheckStart()
}

function createWebSocket () {
  webSocket = new WebSocket('ws://localhost:8080/webSocket/'+userId)
  webSocket.onopen = function () {
    console.log('连接成功...')
    heartCheckStart()
  }
  webSocket.onerror = function () {
    console.log('连接失败...')
    reConnect()
  }
  webSocket.onmessage = function (event) {
    console.log(event.data)
    shouNewMessage(event.data)
    heartCheckReset()
  }
  webSocket.onclose = function (event) {
    console.log('连接已关闭...')
    console.log('websocket 断开: ' + event.code + ' ' + event.reason + ' ' + event.wasClean)
    reConnect()
  }
}

Date.prototype.format = function(fmt) {
     var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt;
}

function sendMsg(){
    var v=$("#message-area").val();
    if(v==""){
        return;
    }else{
        var now = new Date().format("yyyy-MM-dd hh:mm:ss");
        str = v.replace(/\n/gi, "<br/>");
        $("#message-contain-box").append("<div style='width:1168px;overflow:hidden'><div style='font-size:12px;text-align: center;'>"+now+"</div><div class='communication-box' style='float:right'>"+str+"</div></div>");
        var data = $("#receiverId").val()+"——<div style='width:1168px;overflow:hidden'><div style='font-size:12px;text-align: center;'>"+now+"</div><div class='communication-box' style='float:left'>"+str+"</div></div>";
        webSocket.send(data);

    }
}

//显示新消息
function shouNewMessage (data) {
    $("#message-contain-box").append(data);
}


// 重连
function reConnect () {
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  // 没连接上会一直重连，设置延迟避免请求过多
  reTimeoutTimer && clearTimeout(reTimeoutTimer)
  reTimeoutTimer = setTimeout(function () {
    createWebSocket()
    lockReconnect = false
  }, reTimeout)
}

createWebSocket()